<template>
  <div class="app-container">
    <el-card class="mb-3">
      <div slot="header">
        <span>提案统计报告</span>
        <div>
          <el-date-picker
            v-model="selectedMonth"
            type="month"
            placeholder="选择月份"
            value-format="YYYY-MM"
            @change="handleMonthChange"
            style="width: 150px; margin-right: 10px;"
          />
          <el-button @click="resetFilter">重置</el-button>
        </div>
      </div>
      <el-row :gutter="20">
        <el-col :span="24">
          <div class="statistical-board">
            <el-row :gutter="20">
              <el-col :span="4">
                <div class="statistical-item">
                  <div class="statistical-value">{{ totalProposals }}</div>
                  <div class="statistical-label">总提案数</div>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="statistical-item">
                  <div class="statistical-value">{{ highScoreProposals }}</div>
                  <div class="statistical-label">高分提案数 (≥30分)</div>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="statistical-item">
                  <div class="statistical-value">{{ totalScore !== null ? totalScore.toFixed(0) : 'N/A' }}</div>
                  <div class="statistical-label">总分</div>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="statistical-item">
                  <div class="statistical-value">{{ departmentsCount }}</div>
                  <div class="statistical-label">参与部门数</div>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="statistical-item">
                  <div class="statistical-value">{{ totalBonus !== null ? totalBonus.toFixed(0) : 'N/A' }}</div>
                  <div class="statistical-label">总奖金(元)</div>
                </div>
              </el-col>
              <el-col :span="4">
                <div class="statistical-item">
                  <div class="statistical-value">{{ adoptionRate !== null ? adoptionRate.toFixed(1) + '%' : 'N/A' }}</div>
                  <div class="statistical-label">采纳率</div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <el-row :gutter="20">
      <el-col :span="8">
        <el-card>
          <div slot="header">
            <span>各部门提案数量</span>
          </div>
          <div ref="departmentChart" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card>
          <div slot="header">
            <span>高分提案分布</span>
          </div>
          <div ref="scoreChart" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card>
          <div slot="header">
            <span>提案类型分布</span>
          </div>
          <div ref="typeChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt-3">
      <el-col :span="12">
        <el-card>
          <div slot="header">
            <span>各部门总分及参与率</span>
          </div>
          <div ref="avgScoreChart" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <div slot="header">
            <span>提案数量月度趋势</span>
          </div>
          <div ref="monthlyChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-card class="mt-3">
      <div slot="header">
        <span>详细统计数据</span>
      </div>
      <el-table :data="departmentStats" style="width: 100%" border>
        <el-table-column prop="departmentName" label="部门" align="center" />
        <el-table-column prop="proposalCount" label="提案数量" align="center" />
        <el-table-column prop="highScoreCount" label="高分提案数 (≥30)" align="center" />
        <el-table-column prop="totalScore" label="部门总分" align="center">
          <template #default="scope">
            {{ scope.row.totalScore !== null ? scope.row.totalScore.toFixed(0) : 'N/A' }}
          </template>
        </el-table-column>
        <el-table-column prop="maxScore" label="最高评分" align="center" />
        <el-table-column prop="minScore" label="最低评分" align="center" />
        <el-table-column prop="participationRate" label="部门参与率" align="center">
          <template #default="scope">
            {{ scope.row.participationRate !== null ? scope.row.participationRate.toFixed(2) + '%' : 'N/A' }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 前五名高分提案表格 -->
    <el-card class="mt-3">
      <div slot="header">
        <span>高分提案</span>
      </div>
      <el-tabs v-model="top5ActiveTab" @tab-click="handleTop5TabClick">
        <el-tab-pane label="公司" name="company"></el-tab-pane>
        <el-tab-pane v-for="dept in departmentStats" :key="dept.departmentName" :label="dept.departmentName" :name="dept.departmentName"></el-tab-pane>
      </el-tabs>
      <el-table :data="top5Proposals" style="width: 100%" border>
        <el-table-column type="index" label="排名" width="60" align="center" />
        <el-table-column prop="title" label="提案标题" />
        <el-table-column prop="departmentName" label="部门" align="center" />
        <el-table-column prop="proposerName" label="提案人" align="center" />
        <el-table-column prop="finalScore" label="最终评分" align="center" sortable>
          <template #default="scope">
            {{ scope.row.finalScore }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 各部门提案数量矩形图对话框 -->
    <el-dialog title="各部门提案数量矩形图" v-model="departmentTreemapVisible" width="80%" append-to-body>
      <div ref="departmentTreemapChart" class="chart-container-large"></div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance, nextTick, computed } from 'vue'
import * as echarts from 'echarts'
import { listProposals } from '@/api/ciinput/proposal'
import { departmentTotalEmployees } from '@/utils/proposalData';

const { proxy } = getCurrentInstance()

// 数据统计
const totalProposals = ref(0)
const highScoreProposals = ref(0)
const totalScore = ref(null)
const departmentsCount = ref(0)
const totalBonus = ref(null)
const adoptionRate = ref(null)

// 选择的月份
const selectedMonth = ref(null)

// 图表实例
const departmentChart = ref(null)
const scoreChart = ref(null)
const typeChart = ref(null)
const avgScoreChart = ref(null)
const monthlyChart = ref(null)
const departmentTreemapChart = ref(null)
let departmentChartInstance = null
let scoreChartInstance = null
let typeChartInstance = null
let avgScoreChartInstance = null
let monthlyChartInstance = null
let departmentTreemapChartInstance = null

// 部门统计数据
const departmentStats = ref([])

// 所有提案数据
const allProposals = ref([])

// 所有原始提案数据
const originalProposals = ref([])

// 各部门提案数量矩形图可见性
const departmentTreemapVisible = ref(false)

// 前五名高分提案相关
const top5ActiveTab = ref('company')
const top5Proposals = computed(() => {
  // 根据当前选中的tab过滤数据
  let filteredProposals = []
  if (top5ActiveTab.value === 'company') {
    // 全公司数据
    filteredProposals = [...allProposals.value]
  } else {
    // 某个部门的数据
    filteredProposals = allProposals.value.filter(proposal => 
      proposal.departmentName === top5ActiveTab.value
    )
  }

  // 计算最终得分并排序
  const proposalsWithScores = filteredProposals.map(proposal => {
    const finalScore = proposal.committeeTotalScore || proposal.managerTotalScore || proposal.supervisorTotalScore || 0
    return {
      ...proposal,
      finalScore
    }
  })

  // 按分数从高到低排序
  proposalsWithScores.sort((a, b) => b.finalScore - a.finalScore)
  
  // 返回前五名
  return proposalsWithScores.slice(0, 5)
})

// 初始化图表
function initCharts() {
  nextTick(() => {
    if (departmentChart.value) {
      departmentChartInstance = echarts.init(departmentChart.value)
    }
    if (scoreChart.value) {
      scoreChartInstance = echarts.init(scoreChart.value)
    }
    if (typeChart.value) {
      typeChartInstance = echarts.init(typeChart.value)
    }
    if (avgScoreChart.value) {
      avgScoreChartInstance = echarts.init(avgScoreChart.value)
    }
    if (monthlyChart.value) {
      monthlyChartInstance = echarts.init(monthlyChart.value)
    }
    updateCharts()
  })
}


// 更新各部门提案数量矩形图
function updateDepartmentTreemapChart() {
  if (departmentTreemapChartInstance) {
    const departmentData = departmentStats.value.map(item => ({
      name: item.departmentName,
      value: item.proposalCount
    }))
    
    // 按照值从大到小排序
    departmentData.sort((a, b) => b.value - a.value)
    
    const option = {
      title: {
        text: '各部门提案数量',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}个'
      },
      series: [{
        type: 'treemap',
        width: '100%',
        height: '80%',
        top: '10%',
        breadcrumb: {
          show: false
        },
        label: {
          show: true,
          formatter: '{b}\n{c}个',
          fontSize: 14
        },
        itemStyle: {
          borderColor: '#fff'
        },
        data: departmentData
      }]
    }
    
    departmentTreemapChartInstance.setOption(option, true)
  }
}

// 更新图表
function updateCharts() {
  if (departmentChartInstance) {
    const departmentData = departmentStats.value.map(item => ({
      name: item.departmentName,
      value: item.proposalCount
    }))
    
    const departmentOption = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '提案数量',
          type: 'pie',
          radius: '70%',
          center: ['50%', '50%'],
          data: departmentData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    
    departmentChartInstance.setOption(departmentOption, true)
  }
  
  if (scoreChartInstance) {
    const highScoreData = departmentStats.value.map(item => ({
      name: item.departmentName,
      value: item.highScoreCount
    }))
    
    const scoreOption = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '高分提案数',
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['50%', '50%'],
          data: highScoreData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    
    scoreChartInstance.setOption(scoreOption, true)
  }
  
  if (typeChartInstance) {
    // 按提案类型统计
    const typeMap = new Map()
    allProposals.value.forEach(proposal => {
      const typeName = proposal.categoryName || '未指定'
      if (!typeMap.has(typeName)) {
        typeMap.set(typeName, 0)
      }
      typeMap.set(typeName, typeMap.get(typeName) + 1)
    })
    
    const typeData = []
    typeMap.forEach((count, typeName) => {
      typeData.push({ name: typeName, value: count })
    })
    
    const typeOption = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '提案类型',
          type: 'pie',
          radius: '70%',
          center: ['50%', '50%'],
          data: typeData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    
    typeChartInstance.setOption(typeOption, true)
  }
  
   if (avgScoreChartInstance) {
    const departments = departmentStats.value.map(item => item.departmentName)
    const totalScores = departmentStats.value.map(item => item.totalScore || 0)
    const participationRates = departmentStats.value.map(item => item.participationRate !== null ? parseFloat(item.participationRate.toFixed(1)) : 0)
    
    const avgScoreOption = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: function(params) {
          let tooltipText = params[0].name + '<br/>'
          params.forEach(param => {
            if (param.seriesName === '参与率') {
              tooltipText += param.marker + param.seriesName + ': ' + param.value + '%' + '<br/>'
            } else {
              tooltipText += param.marker + param.seriesName + ': ' + param.value + '<br/>'
            }
          })
          return tooltipText
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: departments,
        axisTick: {
          alignWithLabel: true
        }
      },
      yAxis: [
        {
          type: 'value',
          name: '总分'
        },
        {
          type: 'value',
          name: '参与率(%)',
          min: 0,
          max: 100,
          axisLabel: {
            formatter: '{value}%'
          }
        }
      ],
      series: [
        {
          name: '总分',
          type: 'bar',
          barWidth: '60%',
          data: totalScores,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#83bff6' },
              { offset: 0.5, color: '#188df0' },
              { offset: 1, color: '#188df0' }
            ])
          }
        },
        {
          name: '参与率',
          type: 'line',
          yAxisIndex: 1,
          data: participationRates,
          smooth: true,
          itemStyle: {
            color: '#ff7f50'
          }
        }
      ]
    }
    
    avgScoreChartInstance.setOption(avgScoreOption, true)
  }
  
  if (monthlyChartInstance) {
    // 按月份统计提案数量
    const monthMap = new Map()
    originalProposals.value.forEach(proposal => {
      if (proposal.month) {
        const month = proposal.month.substring(0, 7) // YYYY-MM
        if (!monthMap.has(month)) {
          monthMap.set(month, 0)
        }
        monthMap.set(month, monthMap.get(month) + 1)
      }
    })
    
    // 按月份排序
    const sortedMonths = Array.from(monthMap.keys()).sort()
    const monthData = sortedMonths.map(month => ({
      name: month,
      value: monthMap.get(month)
    }))
    
    const monthlyOption = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: sortedMonths,
        axisTick: {
          alignWithLabel: true
        }
      },
      yAxis: {
        type: 'value',
        name: '提案数量'
      },
      series: [{
        name: '提案数量',
        type: 'line',
        data: monthData.map(item => item.value),
        smooth: true,
        itemStyle: {
          color: '#409EFF'
        }
      }]
    }
    
    monthlyChartInstance.setOption(monthlyOption, true)
  }
}

// 处理月份变化
function handleMonthChange(value) {
  console.log('选择的月份:', value);
  filterProposalsByMonth(value)
}

// 根据选择的月份过滤提案
function filterProposalsByMonth(month) {
  //console.log('过滤数据，月份:', month);
  if (!month) {
    // 如果没有选择月份，使用所有提案
    //console.log('使用所有提案数据');
    calculateStats(originalProposals.value)
  } else {
    // 根据选择的月份过滤提案
    const filteredProposals = originalProposals.value.filter(proposal => {
      const proposalMonth = proposal.month ? proposal.month.substring(0, 7) : null;
      //console.log('提案月份:', proposalMonth, '筛选月份:', month);
      return proposalMonth === month;
    })
    //console.log('筛选后的提案数量:', filteredProposals.length);
    calculateStats(filteredProposals)
  }
}

// 重置筛选条件
function resetFilter() {
  selectedMonth.value = null
  calculateStats(originalProposals.value)
}

// 过滤掉未审核完成的提案（最终成绩为0或空）
function filterValidProposals(proposals) {
  return proposals.filter(proposal => {
    const finalScore = proposal.committeeTotalScore || proposal.managerTotalScore || proposal.supervisorTotalScore || 0
    return finalScore > 0
  })
}

// 计算统计数据
function calculateStats(proposals) {
  //console.log('计算统计数据，提案数量:', proposals.length);
  // 过滤掉未审核完成的提案
  const validProposals = filterValidProposals(proposals)
  //console.log('有效提案数量:', validProposals.length);
  
  // 保存所有有效提案数据
  allProposals.value = validProposals
  
  // 总提案数
  totalProposals.value = validProposals.length
  
  // 高分提案数 (总分 >= 30)
  highScoreProposals.value = validProposals.filter(proposal => {
    const totalScore = proposal.committeeTotalScore || proposal.managerTotalScore || proposal.supervisorTotalScore || 0
    return totalScore >= 30
  }).length
  
  // 总分
  const scores = validProposals.map(proposal => {
    return proposal.committeeTotalScore || proposal.managerTotalScore || proposal.supervisorTotalScore || 0
  }).filter(score => score > 0)
  
  if (scores.length > 0) {
    totalScore.value = scores.reduce((a, b) => a + b, 0)
  } else {
    totalScore.value = null
  }
  
  // 总奖金
  const bonuses = validProposals.map(proposal => proposal.bonus || 0)
  totalBonus.value = bonuses.reduce((a, b) => a + b, 0)
  
  // 采纳率 (有评分的提案视为已采纳)
  if (proposals.length > 0) {
    adoptionRate.value = (validProposals.length / proposals.length) * 100
  } else {
    adoptionRate.value = null
  }
  
  // 按部门统计
  const deptMap = new Map()
  
  // 用于跟踪每个部门的提案人
  const deptProposersMap = new Map()

  validProposals.forEach(proposal => {
    const deptName = proposal.departmentName || '未指定'
    if (!deptMap.has(deptName)) {
      deptMap.set(deptName, {
        departmentName: deptName,
        proposalCount: 0,
        highScoreCount: 0,
        scores: [],
        bonuses: []
      })
      deptProposersMap.set(deptName, new Set())
    }
    
    const dept = deptMap.get(deptName)
    dept.proposalCount++
    
    // 添加提案人到集合中
    if (proposal.proposerName) {
          deptProposersMap.get(deptName).add(proposal.proposerName)
        }

    // 高分提案计数
    const totalScore = proposal.committeeTotalScore || proposal.managerTotalScore || proposal.supervisorTotalScore || 0
    if (totalScore >= 30) {
      dept.highScoreCount++
    }
    
    // 收集评分和奖金
    if (totalScore > 0) {
      dept.scores.push(totalScore)
    }
    if (proposal.bonus) {
      dept.bonuses.push(proposal.bonus)
    }
  })
  
  // 计算各部门统计数据
  const stats = []
  deptMap.forEach((dept, deptName) => {
    const stat = {
      departmentName: dept.departmentName,
      proposalCount: dept.proposalCount,
      highScoreCount: dept.highScoreCount
    }
    
    // 计算部门总分、最高分、最低分
    if (dept.scores.length > 0) {
      stat.totalScore = dept.scores.reduce((a, b) => a + b, 0)
      stat.maxScore = Math.max(...dept.scores)
      stat.minScore = Math.min(...dept.scores)
    } else {
      stat.totalScore = null
      stat.maxScore = null
      stat.minScore = null
    }
    
    // 计算部门参与率 
    const totalDepartmentEmployees = departmentTotalEmployees[deptName]
    const uniqueProposersCount = deptProposersMap.get(deptName).size
    stat.participationRate = totalDepartmentEmployees > 0 ? (uniqueProposersCount / totalDepartmentEmployees) * 100 : 0
    
    stats.push(stat)
  })
  
  departmentStats.value = stats
  departmentsCount.value = stats.length
  
  //console.log('部门统计数据:', stats);
  
  // 更新图表
  updateCharts()
}

// 获取数据
async function fetchData() {
  try {
    // 获取所有已完成评分的提案数据
    const response = await listProposals({ scoreStatus: 'scored' })
    //console.log('获取到的提案数据:', response.rows);
    // 保存原始数据
    originalProposals.value = response.rows
    // 初始计算所有数据的统计信息
    calculateStats(response.rows)
  } catch (error) {
    console.error('获取提案数据失败:', error)
    proxy.$modal.msgError('获取数据失败: ' + (error.message || error))
  }
}

// 窗口大小改变时重置图表
function handleResize() {
  if (departmentChartInstance) {
    departmentChartInstance.resize()
  }
  if (scoreChartInstance) {
    scoreChartInstance.resize()
  }
  if (typeChartInstance) {
    typeChartInstance.resize()
  }
  if (avgScoreChartInstance) {
    avgScoreChartInstance.resize()
  }
  if (monthlyChartInstance) {
    monthlyChartInstance.resize()
  }
  if (departmentTreemapChartInstance) {
    departmentTreemapChartInstance.resize()
  }
}

// 处理前五名tab点击事件
function handleTop5TabClick(tab) {
  // 确保正确设置tab名称
  top5ActiveTab.value = tab.paneName || tab.name
}

onMounted(() => {
  fetchData()
  initCharts()
  window.addEventListener('resize', handleResize)
})

// 组件销毁前移除事件监听
window.addEventListener('beforeunload', () => {
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 300px;
}

.chart-container-large {
  width: 100%;
  height: 600px;
}

.statistical-board {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 20px;
}

.statistical-item {
  text-align: center;
  padding: 15px 0;
}

.statistical-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.statistical-label {
  font-size: 12px;
  color: #606266;
  margin-top: 5px;
}

.mt-3 {
  margin-top: 20px;
}

.mb-3 {
  margin-bottom: 20px;
}
</style>